from django.shortcuts import render
from django.http import HttpResponse


from .. models import Users

from django.contrib.auth.models import User,Permission,Group

from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import permission_required

# Create your views here.
def index(request):
    return render(request,'admin/index.html')

# 管理员列表

def authuser(request):
    # 获取所有的管理员
    obs = User.objects.all()

    context = {'ulist':obs}

    return render(request,'admin/auth/user.html',context)


# 管理员添加

def authuseradd(request):
    if request.method == 'GET':
        # 获取所有的组
        obs = Group.objects.all()
        context = {'glist':obs}

        return render(request,'admin/auth/useradd.html',context)

    elif request.method == 'POST':

        # 创建普通管理员
        myuser = User.objects.create_user(
            request.POST['username'],
            request.POST['email'],
            request.POST['password']
        )

        # 获取选择的组
        gs = request.POST.getlist('gs')
        print(gs)
        # 判断是否设置了所属组
        if gs:
            # 根据选择的组,获取组对象
            obs = Group.objects.filter(id__in=gs)
            # 给用户设置所在组
            myuser.groups.set(obs)
            print(obs)


        return HttpResponse('<script>alert("创建成功");location.href="/myadmin/auth/user/"</script>')

# 组列表

def authgroup(request):

    # 获取所有的组
    obs = Group.objects.all()

    # 分配数据
    context = {'glist':obs}

    return render(request,'admin/auth/group.html',context)



# 创建组

def authgroupadd(request):
    if request.method == 'GET':
        # 读取所有权限信息,并排除以Can开头的系统默认生成权限
        obs = Permission.objects.exclude(name__istartswith='Can')
        context = {'plist':obs}
        return render(request,'admin/auth/groupadd.html',context)

    elif request.method == 'POST':
        #接受参数
        # 组名
        name = request.POST['name']
        prms = request.POST.getlist('prms')

        # 第一步 先创建组对象
        group = Group()
        group.name = name
        group.save()

        # 判断是否选择的权限
        if prms:
            # 第二步 给组设置权限
            # 根据选择的权限,获取权限对象
            prmsobjs = Permission.objects.filter(id__in=prms)
            # 设置权限
            group.permissions.set(prmsobjs)
            group.save()


        return HttpResponse('<script>alert("创建成功");location.href="/myadmin/auth/group/"</script>')


# 组修改

def authgroupedit(request,gid):
    # 根据id获取组对象 
    ob = Group.objects.get(id=gid)

    if request.method == 'GET':
        # 获取当前组已经选择的权限之外的所有权限
        plist = Permission.objects.exclude(name__istartswith="Can").exclude(id__in=ob.permissions.all())
        # 分配数据
        context = {'ginfo':ob,'plist':plist}
        # 加载模板
        return render(request,'admin/auth/groupedit.html',context)

    elif request.method == 'POST':
        # 修改组
        ob.name = request.POST['name']
        ob.save()

        # 修改组权限
        # 清空当前组权限
        ob.permissions.clear()
        prms = request.POST.getlist('prms')
        # 判断是否选择的权限
        if prms:
            # 第二步 给组设置权限
            # 根据选择的权限,获取权限对象
            prmsobjs = Permission.objects.filter(id__in=prms)
            # 设置权限
            ob.permissions.set(prmsobjs)
            ob.save()
        return HttpResponse('<script>alert("编辑成功");location.href="/myadmin/auth/group/"</script>')




# 登录
def adminlogin(request):
    
    # 判断请求方式如果为GET 返回一个登录页面
    if request.method == 'GET':

        return render(request,'admin/login.html')
    elif request.method == 'POST':
     
        # 判断验证码是否正确
        if request.POST['vcode'].upper() != request.session['verifycode'].upper():
            return HttpResponse('<script>alert("验证码错误");history.back(-1);</script>')



        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            # 登录
            login(request, user)
            
            request.session['AdminUser'] = {'uid':user.id,'uname':user.username}

            return HttpResponse('<script>alert("欢迎登陆");location.href="/myadmin/"</script>')

        else:
            return HttpResponse('<script>alert("用户名或密码错误");history.back(-1);</script>')

# 退出登录
def adminlogout(request):
    request.session['AdminUser'] = ''

    return HttpResponse('<script>alert("退出成功,欢迎下次登陆");location.href="/myadmin/login/"</script>')


# 验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')